package com.ly.blog2backup.utils;

import com.ly.blog2Common.utils.StringUtils;
import com.ly.blog2backup.constants.FileConstants;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author: lyMaster
 * @time: 2020/7/28 17:00
 */
public class ImageFileUtils {

    public static String HTTP = FileConstants.HEADER + FileConstants.IP + ":"+FileConstants.PORT + FileConstants.URL;

    /**
     * 图片文件特殊公共处理点  -- s
     */

    /**
     * Base64转图片文件
     * @param imgBase64
     * @param filePath 文件路径 包含 \
     * @param imgName
     * @return 文件 src
     */
    public static String saveImgFileByBase64(String imgBase64,String filePath,String imgName) {
        if (StringUtils.isBlank(imgBase64)) { // 图像数据为空
            return "";
        }

        if (imgBase64.matches("/.*\\.\\w+")) { // 图像数据为 url 直接返回  /开头 有.号 多个字母结尾
            return imgBase64;
        }

        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }

        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            // Base64解码  

            imgName = imgName + "." + imgBase64.split(";base64,")[0].split("image/")[1];
            String base = imgBase64.split(";base64,")[1];

            byte[] b = decoder.decodeBuffer(base);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }

            //检测文件是否已加载
            out = new FileOutputStream(filePath +imgName);
            out.write(b);
        } catch (Exception e) {
            e.printStackTrace();
            return imgBase64;
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return HTTP + imgName;
    }

    /**
     * 检测图片base64数据是否已经存在 ，存在不修改 - 不存在修改
     * 返回路径
     */
    public static String base64IsExistInFileAndReturnPath(String imgBase64, String filePath, String imgName_) {
        if (StringUtils.isBlank(imgBase64)) { // 图像数据为空
            return null;
        }

        if (imgBase64.matches("/.*\\.\\w+")) { // 图像数据为 url 直接返回  /开头 有.号 多个字母结尾
            return imgBase64;
        }

        File file = new File(filePath);

        OutputStream out = null;
        BASE64Decoder decoder = new BASE64Decoder();
        String originMD5 = "";
        try {
            // Base64解码  

            if (!file.exists()) {
                file.mkdirs();
            }

            String imgName = imgName_ + "." + imgBase64.split(";base64,")[0].split("image/")[1];
            String base = imgBase64.split(";base64,")[1];

            byte[] b = decoder.decodeBuffer(base);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            //检测文件是否已加载
            File originFile = new File(filePath + File.separatorChar + imgName);
            out = new FileOutputStream(originFile);
            out.write(b);
            originMD5 = getMD5(originFile);


            File[] files = file.listFiles();
//            for (File f : files) {
//                String arrayFileMD5 = getMD5(f);
//                if (originMD5.equals(arrayFileMD5)) {
//                    originFile.delete();
//                    return ViewConstant.ARTICLE_IMG + "/"
//                            + f.getPath().substring(f.getPath().lastIndexOf(File.separatorChar) + 1, f.getPath().length());
//                }
//            }
//            return ViewConstant.ARTICLE_IMG + "/" + imgName;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 文件MD5转换
     */
    public static String getMD5(File read) throws NoSuchAlgorithmException, IOException {
        InputStream in = null;
        try {
            in = new FileInputStream(read);
            StringBuffer md5 = new StringBuffer();
            MessageDigest md = MessageDigest.getInstance("MD5");

            byte[] daraBytes = new byte[1024];
            int readN = 0;
            while ((readN = in.read(daraBytes)) != -1){
                md.update(daraBytes,0,readN);
            }

            byte[] mdbytes = md.digest();
            for(int i=0; i<mdbytes.length;i++){
                md5.append(Integer.toString((mdbytes[i] & 0xff) + 0x100,16).substring(1));
            }
            return md5.toString().toLowerCase();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



    /**
     * 图片文件特殊公共处理点  -- e
     */



}
